/* 
 *  File: utils_impl.cpp
 *  Project: apsdk
 *  Created: Oct 25, 2018
 *  Author: Sheen Tian
 *  
 *  This file is part of apsdk (https://github.com/air-display/apsdk-public) 
 *  Copyright (C) 2018-2024 Sheen Tian 
 *  
 *  apsdk is free software: you can redistribute it and/or modify it under the terms 
 *  of the GNU General Public License as published by the Free Software Foundation, 
 *  either version 3 of the License, or (at your option) any later version.
 *  
 *  apsdk is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 *  See the GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License along with Foobar. 
 *  If not, see <https://www.gnu.org/licenses/>.
 */

#include "../logger.h"
#include "../utils.h"

void set_thread_name(void *t, const char *name) {}

static JavaVM *g_jvm = nullptr;
void setGlobalJavaVM(JavaVM *vm) { g_jvm = vm; }

JavaVM *getGlobalJavaVM() { return g_jvm; }

void attachCurrentThreadToJvm() {
  JavaVM *vm = getGlobalJavaVM();
  if (vm) {
    JavaVMAttachArgs args;
    args.version = JNI_VERSION_1_6;
    args.name = 0;
    args.group = 0;
    JNIEnv *env = 0;
    int status = vm->AttachCurrentThread(&env, &args);
    if (JNI_OK != status) {
      LOGE() << "Failed to attach the thread";
    }
  }
}

void detachCurrentThreadFromJvm() {
  JavaVM *vm = getGlobalJavaVM();
  if (vm) {
    vm->DetachCurrentThread();
  }
}
